package com.by.hazelcasttopic;

import com.alibaba.fastjson2.JSON;
import com.by.hazelcasttopic.consts.HazelcastConst;
import com.by.toolkit.platform.ByContext;
import com.google.common.collect.Maps;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.topic.ITopic;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

import static com.by.toolkit.utils.ExceptionUtil.nullError;

@Slf4j
public class HazelcastTopic {

    private static final Map<String, HazelcastInstance> HAZELCAST_INSTANCE = Maps.newHashMap();

    public void setInstances(Map<String, HazelcastInstance> instanceMap) {
        log.info("[HazelcastTopic][setInstances] instanceMap:[{}]", instanceMap);
        HAZELCAST_INSTANCE.putAll(instanceMap);
        log.info("[HazelcastTopic][setInstances] HAZELCAST_INSTANCE:[{}]", HAZELCAST_INSTANCE);

    }

    public static void publishTopic(String topicName, Map<String, Object> message) {
        HazelcastInstance hazelcastInstance = HAZELCAST_INSTANCE.get(topicName);
        nullError(hazelcastInstance, "广播实例[{}]为空！", topicName);

        ITopic<String> topic = hazelcastInstance.getTopic(topicName);
        Map<String, String> context = ByContext.getAll();

        Map<String, Object> newMessageMap = Maps.newHashMap(message);
        newMessageMap.put(HazelcastConst.BY_CONTEXT, context);
        newMessageMap.put(HazelcastConst.TOPIC_NAME, topicName);
        String messageJsonStr = JSON.toJSONString(newMessageMap);
        topic.publish(messageJsonStr);
        log.info("[HazelcastTopic][publishTopic] topicName:[{}] messageJson:[{}]", topicName, messageJsonStr);
    }


}
